#pragma once
#include <iostream>
using namespace std;
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string>
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <functional>

// 用户的信息：ip和端口
class User
{
public:
    User(const string &ip, const uint16_t &port) : _ip(ip), _port(port)
    {
    }

    ~User()
    {
    }

    string ip()
    {
        return _ip;
    }
    uint16_t port()
    {
        return _port;
    }

public:
    string _ip;
    uint16_t _port;
};

// 类中包含类
// 在线的用户：先描述，再组织，上面是对用户的描述，下面利用字典对用户组织
class OnlineUser
{
public:
    OnlineUser()
    {
    }

    void addUser(const string &ip, const uint16_t &port)
    {
        string id = ip + "-" + to_string(port);
        _users.insert(make_pair(id, User(ip, port)));
    }

    void delUser(const string &ip, const uint16_t &port)
    {
        string id = ip + "-" + to_string(port);
        _users.erase(id); // 删除传key值就可以
    }

    bool isOnline(const string &ip, const uint16_t &port)
    {
        // 通过key去找value
        string id = ip + "-" + to_string(port);
        return _users.find(id) == _users.end() ? false : true;
    }

    void broadcastMessage(int sockfd, const string &ip, const uint16_t &port, const string &message)
    {
        for (auto &e : _users)
        {
            //给所有人发送信息
            struct sockaddr_in client;
            bzero(&client, sizeof(client));

            client.sin_family = AF_INET;
            client.sin_port = htons(e.second.port());
            client.sin_addr.s_addr = inet_addr(e.second.ip().c_str());

            string s = ip + "-" + to_string(port) + "# ";
            s += message;

            sendto(sockfd, s.c_str(), s.size(), 0, (sockaddr *)&client, sizeof(client));
        }
    }
    ~OnlineUser()
    {
    }

private:
    unordered_map<string, User> _users;
};